﻿
using GCC.APIContainer.Utilities;
using GCC.Container.Abstracts;
using GCC.Container.Models;

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

using TTGIS.TileServer.API.ApiModels;
using TTGIS.TileServer.API.MapInfoFiles;

namespace TTGIS.TileServer.API
{
    /// <summary>
    /// 工具服务
    /// </summary>
    [ApiController]
    [Route("GISTools/[controller]")]
    public class DataFileReaderController : GCCAPIControllerBase
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="context"></param>
        public DataFileReaderController(AbsGCCContext context) : base(context)
        {
        }

        /// <summary>
        /// 根据投影平面笛卡尔坐标获取卫星图瓦片
        /// </summary>  
        /// <param name="mid">mid文件</param>
        /// <param name="mif">mif文件</param>
        /// <param name="midEncoding">数据文件编码</param>
        /// <returns></returns>
        [HttpPost("mapInfo/mif")]
        public DataResponse<GetDataInfoFromMifResponse> GetDataInfoFromMif(IFormFile mif, IFormFile mid, [FromQuery] string? midEncoding = "gb2312")
        {
            if (mif is null || mid is null)
            {
                return IllegalRequest<GetDataInfoFromMifResponse>();
            }

            string? mifFilePath;
            {
                var fileFolderPath = Path.Combine(AppContext.BaseDirectory, Guid.NewGuid().ToString("N"));
                mifFilePath = Path.Combine(fileFolderPath, mif.FileName);
                _ = Directory.CreateDirectory(fileFolderPath);
                {
                    using var fs = System.IO.File.Open(mifFilePath, FileMode.CreateNew, FileAccess.ReadWrite);
                    mif.CopyTo(fs);
                    fs.Flush();
                    fs.Close();
                }
            }


            string? midFilePath;
            {
                var fileFolderPath = Path.Combine(AppContext.BaseDirectory, Guid.NewGuid().ToString("N"));
                midFilePath = Path.Combine(fileFolderPath, mid.FileName);
                _ = Directory.CreateDirectory(fileFolderPath);
                {
                    using var fs = System.IO.File.Open(midFilePath, FileMode.CreateNew, FileAccess.ReadWrite);
                    mid.CopyTo(fs);
                    fs.Flush();
                    fs.Close();
                }
            }
            return HandleData(new GetDataFromFile().GetData(mifFilePath, midFilePath, midEncoding));
        }
    }
}
